#!/bin/bash

source config.sh

# MySQL 5.7 Docker自动安装配置脚本（使用华为云SWR镜像）

# 检查Docker是否安装
check_docker() {
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}错误: Docker未安装，请先安装Docker${NC}"
        exit 1
    fi
}

# 检查并创建网络
create_network() {
    if ! docker network inspect $DOCKER_NETWORK &> /dev/null; then
        echo -e "${YELLOW}创建Docker网络: ${DOCKER_NETWORK}...${NC}"
        docker network create $DOCKER_NETWORK
    fi
}

# 检查并创建数据卷
create_volume() {
    if ! docker volume inspect $DATA_VOLUME &> /dev/null; then
        echo -e "${YELLOW}创建数据卷: ${DATA_VOLUME}...${NC}"
        docker volume create $DATA_VOLUME
    fi
}

# 检查并启动MySQL容器
setup_mysql() {
    # 检查容器是否已存在
    if docker ps -a --format '{{.Names}}' | grep -q "^${MYSQL_CONTAINER_NAME}\$"; then
        if docker ps --format '{{.Names}}' | grep -q "^${MYSQL_CONTAINER_NAME}\$"; then
            echo -e "${GREEN}MySQL容器已在运行中${NC}"
            return
        else
            echo -e "${YELLOW}启动已存在的MySQL容器...${NC}"
            docker start $MYSQL_CONTAINER_NAME
            return
        fi
    fi

    echo -e "${YELLOW}从华为云SWR拉取MySQL 5.7镜像...${NC}"
    docker pull $MYSQL_IMAGE

    echo -e "${YELLOW}启动MySQL容器...${NC}"
    docker run -d \
        --name $MYSQL_CONTAINER_NAME \
        --network $DOCKER_NETWORK \
        -p $MYSQL_PORT:3306 \
        -e MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD \
        -v $DATA_VOLUME:/var/lib/mysql \
        $MYSQL_IMAGE \
        --character-set-server=utf8mb4 \
        --collation-server=utf8mb4_unicode_ci \
        --default-authentication-plugin=mysql_native_password

    # 等待MySQL启动
    echo -e "${YELLOW}等待MySQL启动(约30秒)...${NC}"
    for i in {1..30}; do
        if docker logs $MYSQL_CONTAINER_NAME 2>&1 | grep -q "ready for connections"; then
            break
        fi
        sleep 1
    done

    # 配置root远程访问权限
    echo -e "${YELLOW}配置root用户远程访问权限...${NC}"
    docker exec $MYSQL_CONTAINER_NAME mysql -uroot -p$MYSQL_ROOT_PASSWORD -e \
        "CREATE USER IF NOT EXISTS 'root'@'%' IDENTIFIED BY '${MYSQL_ROOT_PASSWORD}'; \
        GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION; \
        FLUSH PRIVILEGES;"
}

# 显示连接信息
show_info() {
    LOCAL_IP=$(hostname -I | awk '{print $1}')
    echo -e "${GREEN}MySQL 5.7 已成功部署!${NC}"
    echo -e "连接信息:"
    echo -e "  - 容器名称: ${MYSQL_CONTAINER_NAME}"
    echo -e "  - 主机: ${LOCAL_IP} 或 127.0.0.1"
    echo -e "  - 端口: ${MYSQL_PORT}"
    echo -e "  - 用户名: root"
    echo -e "  - 密码: ${MYSQL_ROOT_PASSWORD}"
    echo -e "  - Docker网络: ${DOCKER_NETWORK}"
    echo -e "  - 数据卷: ${DATA_VOLUME}"
    echo -e "  - 使用的镜像: ${MYSQL_IMAGE}"
}

# 主执行流程
echo -e "${YELLOW}开始MySQL 5.7 Docker安装配置(使用华为云SWR镜像)...${NC}"

check_docker
create_network
create_volume
setup_mysql
show_info

echo -e "${GREEN}脚本执行完成!${NC}"
echo -e "${YELLOW}测试连接命令: mysql -h 127.0.0.1 -P 3306 -u root -p${MYSQL_ROOT_PASSWORD}${NC}"